iT邦幫忙

2022 iThome 鐵人賽

DAY 4
0
自我挑戰組

SPRING BOOT系列 第 5

掌握關係對應開發, 實現一對一對應

  • 分享至 

  • xImage
  •  

物件關係對應(OBJECT RELATIONAL MAPPING) 是指透過將物件狀態對應到資料庫列,來開發和維護物件和官料庫之間的關係。他能夠輕鬆處裡各種資料庫操作。例如:插入、更新、刪除。
除了一對一

之外

還有 一對多

跟多對多

目前縣介紹最常用的 一對一:實體的每個實例與另一個實體的單一實例相連結。

考慮資料表結構,還要考慮實體關西的方向性。
若為雙向連結, 則在儲存實體關係中要配合 註解 @JoinColumn

在沒有儲存實體關係的實體中,要用mappedBy屬性明確所連結的實體

對應方向:
ORM的對應方向是表與表連結(JOIN),可分為兩種。
單向關西與雙向關系

@OneToOne:
student 實例


import lombok.Data;
import javax.persistence.*;

@Entity
@Data
@Table(name = "stdu")
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String name;
    @Column(columnDefinition = "enum('male','female')")
    private String sex;
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "card_id")
     private Card card;
}

新增CARD實例

package com.example.demo.entity;

import lombok.Data;
import javax.persistence.*;



@Entity
@Table(name = "card")
@Data
public class Card {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private Integer num;
 }

撰寫Repository層級

package com.example.demo.repository;


import com.example.demo.entity.Card;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;


public interface CardRepository extends JpaRepository<Card,Long>  , JpaSpecificationExecutor<Card> {
    Card findById(long id);

}

新增student實體

package com.example.demo.repository;


import com.example.demo.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import javax.transaction.Transactional;


public interface StudentRepository extends JpaRepository<Student, Long> {
    Student findById(long id);
    Student deleteById(long id);
    @Query("select a from Student a where a.name = ?1")
    Student getStudentByMySelf(String name);
    @Query(value = "select * from stdu a where a.name = ?1",nativeQuery = true)
    Student getStudentByMySelf2(String name);

    @Modifying
    @Transactional
    @Query(value = "update Student a set a.name = 'JACK' where a.id =:id")
    void updataUserByGuid(@Param("id") long id);
    @Modifying
    @Transactional
    @Query(value = "update Student a set a.name = :name where a.id =:id")
    void updataStudentById(@Param("name") String name, @Param("id") long id);

}

CARD REPOSITORY

package com.example.demo.repository;


import com.example.demo.entity.Card;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;


public interface CardRepository extends JpaRepository<Card,Long>  , JpaSpecificationExecutor<Card> {
    Card findById(long id);

}

寫SERVER層級

package com.example.demo.service;



import com.example.demo.entity.Card;

import java.util.List;

public interface CardService {
    public List<Card> getCardList();
    public Card findCardById(long id);
}

package com.example.demo.service;


import com.example.demo.entity.Student;

import java.util.List;

public interface StudentService {
    public List<Student> getStudentlist();
    public Student findStudentById(long id);
}

serviceImpl written

package com.example.demo.service.impl;


import com.example.demo.entity.Card;
import com.example.demo.repository.CardRepository;
import com.example.demo.service.CardService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class CardServiceImpl implements CardService {
    @Autowired
    private CardRepository cardRepository;

    @Override
    public List<Card> getCardList() {
        return cardRepository.findAll();
    }

    @Override
    public Card findCardById(long id) {
        return cardRepository.findById(id);
    }
}


package com.example.demo.service.impl;


import com.example.demo.entity.Student;
import com.example.demo.repository.StudentRepository;
import com.example.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentRepository studentRepository;
    @Override
    public List<Student> getStudentlist() {
        return studentRepository.findAll();
    }

    @Override
    public Student findStudentById(long id) {
        return studentRepository.findById(id);
    }



}


SpringBootApplication
JpaOneToOneDemoApplication

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class JpaOneToOneDemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(JpaOneToOneDemoApplication.class, args);
	}

}

撰寫測試:

package com.example.demo.entity;

import com.example.demo.repository.CardRepository;
import com.example.demo.repository.StudentRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import static org.junit.Assert.*;


@SpringBootTest
@RunWith(SpringRunner.class)
public class oneToOneTest {
    @Autowired
    private StudentRepository studentRepository;
    @Autowired
    private CardRepository cardRepository;

    @Test
    public void testOneToOne() {
        Student student1 = new Student();
        student1.setName("MAKE");
        student1.setSex("male");
        Student student2 = new Student();
        student2.setName("BOYACOOL");
        student2.setSex("male");

        Card card1 = new Card();
        card1.setNum(422802);
        student1.setCard(card1);
        studentRepository.save(student1);
        studentRepository.save(student2);
        Card card2 = new Card();
        card2.setNum(422803);
        cardRepository.save(card2);
       
        Long id = student1.getId();
        
        studentRepository.deleteById(id);
    }


}


上一篇
JPA來做 建置一張報紙範例資料表 LV.2:殺完史萊姆開始殺豪豬
系列文
SPRING BOOT5
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言